<template>
  <div class="forum-detail-container">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="论坛详情"
      left-text="返回"
      left-arrow
      @click-left="handleBack"
      class="forum-detail-header"
    />

    <!-- 帖子内容区域 -->
    <div class="post-content">
      <!-- 标题 -->
      <h1 class="post-title">{{ postDetail.title }}</h1>
      
      <!-- 作者信息和发布时间 -->
      <div class="author-info">
        <van-image :src="postDetail.user?.avatar" class="avatar" round />
        <div class="author-details">
          <span class="username">{{ postDetail.user?.username }}</span>
          <span class="post-time">{{ formatTime(postDetail.createdAt) }}</span>
        </div>
      </div>
      
      <!-- 帖子正文 -->
      <div class="post-text">{{ postDetail.content }}</div>
      
      <!-- 封面图 -->
      <van-image 
        v-if="postDetail.coverImage"
        :src="postDetail.coverImage"
        class="cover-image"
        fit="contain"
      />
      <!-- 互动数据 -->
      <div class="interaction-data">
        <div class="interaction-item">
          <van-icon name="like-o" class="interaction-icon" />
          <span class="interaction-count">{{ postDetail.likes }}</span>
        </div>
        <div class="interaction-item">
          <van-icon name="star-o" class="interaction-icon" />
          <span class="interaction-count">{{ postDetail.collects }}</span>
        </div>
        <div class="interaction-item">
          <van-icon name="comment-o" class="interaction-icon" />
          <span class="interaction-count">{{ postDetail.comments }}</span>
        </div>
      </div>
    </div>

    <!-- 评论区域 -->
    <div class="comments-section">
      <h2 class="comments-title">评论 ({{ allComments.length }})</h2>
      <div class="comments-list">
        <!-- 主评论 -->
        <div v-for="comment in mainComments" :key="comment.commentId" class="comment-item">
          <!-- 评论人信息 -->
          <div class="comment-author-info">
            <van-image :src="comment.user?.avatar" class="comment-avatar" round />
            <div class="comment-author-details">
              <span class="comment-username">{{ comment.user?.username }}</span>
              <span class="comment-time">{{ formatTime(comment.createdAt) }}</span>
            </div>
          </div>
          <!-- 评论内容 -->
          <div class="comment-content">{{ comment.content }}</div>
          <!-- 评论操作 -->
          <div class="comment-actions">
            <span class="comment-action" @click="showReplyInput(comment)">回复</span>
          </div>
          
          <!-- 子评论列表 -->
          <div v-if="getSubComments(comment.commentId).length > 0" class="sub-comments">
            <div v-for="subComment in getSubComments(comment.commentId)" :key="subComment.commentId" class="sub-comment-item">
              <div class="sub-comment-inner">
                <div class="sub-comment-author-info">
                  <van-image :src="subComment.user?.avatar" class="sub-comment-avatar" round />
                  <div class="sub-comment-author-details">
                    <span class="sub-comment-username">{{ subComment.user?.username }}</span>
                    <span class="sub-comment-time">{{ formatTime(subComment.createdAt) }}</span>
                  </div>
                </div>
                <div class="sub-comment-content">
                  <span v-if="subComment.parentCommentUser" class="reply-to">回复 @{{ subComment.parentCommentUser?.username }}：</span>
                  {{ subComment.content }}
                </div>
                <div class="sub-comment-actions">
                  <span class="sub-comment-action" @click="showReplyInput(subComment, comment)">回复</span>
                </div>
              </div>
              
              <!-- 子评论的回复输入框 -->
              <div v-if="replyingTo === subComment.commentId" class="sub-reply-input-container">
                <van-field 
                  v-model="replyText"
                  :placeholder="`回复 @${subComment.user?.username}`"
                  class="reply-input"
                  show-word-limit
                  maxlength="200"
                />
                <div class="reply-buttons">
                  <van-button @click="cancelReply" class="cancel-button">取消</van-button>
                  <van-button @click="submitReply(subComment, comment)" class="submit-reply-button">发送</van-button>
                </div>
              </div>
              
              <!-- 子评论的回复列表 -->
              <div v-if="getSubComments(subComment.commentId).length > 0" class="sub-sub-comments">
                <div v-for="subSubComment in getSubComments(subComment.commentId)" :key="subSubComment.commentId" class="sub-sub-comment-item">
                  <div class="sub-sub-comment-inner">
                    <div class="sub-sub-comment-author-info">
                      <van-image :src="subSubComment.user?.avatar" class="sub-sub-comment-avatar" round />
                      <div class="sub-sub-comment-author-details">
                        <span class="sub-sub-comment-username">{{ subSubComment.user?.username }}</span>
                        <span class="sub-sub-comment-time">{{ formatTime(subSubComment.createdAt) }}</span>
                      </div>
                    </div>
                    <div class="sub-sub-comment-content">
                      <span v-if="subSubComment.parentCommentUser" class="reply-to">回复 @{{ subSubComment.parentCommentUser?.username }}：</span>
                      {{ subSubComment.content }}
                    </div>
                    <div class="sub-sub-comment-actions">
                      <span class="sub-sub-comment-action" @click="showReplyInput(subSubComment, comment)">回复</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 主评论的回复输入框 -->
          <div v-if="replyingTo === comment.commentId" class="reply-input-container">
            <van-field 
              v-model="replyText"
              :placeholder="`回复 @${comment.user?.username}`"
              class="reply-input"
              show-word-limit
              maxlength="200"
            />
            <div class="reply-buttons">
              <van-button @click="cancelReply" class="cancel-button">取消</van-button>
              <van-button @click="submitReply(comment)" class="submit-reply-button">发送</van-button>
            </div>
          </div>
        </div>
        <div v-if="allComments.length === 0" class="no-comments">
          暂无评论，快来抢沙发吧～
        </div>
      </div>
    </div>

    <!-- 底部评论输入框 -->
    <div class="comment-input-section">
      <van-field 
        v-model="commentText"
        placeholder="写下你的评论..."
        class="comment-input"
        show-word-limit
        maxlength="200"
      />
      <van-button @click="submitComment" class="submit-button">发送</van-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from "@/utils/axios.js";
import {useUserStore} from "@/stores/user.js";

const router = useRouter();
const route = useRoute();
const postId = route.query.id;

// 帖子详情数据
const postDetail = ref({
  postId: 0,
  title: '',
  coverImage: '',
  content: '',
  authorId: 0,
  likes: 0,
  collects: 0,
  comments: 0,
  createdAt: '',
  status: '',
  user: {
    userId: 0,
    username: '',
    avatar: ''
  }
});

// 所有评论数据
const allComments = ref([]);

// 评论输入内容
const commentText = ref('');
// 回复相关数据
const replyText = ref('');
const replyingTo = ref(null);

// 计算主评论（没有parentCommentId的评论）
const mainComments = computed(() => {
  return allComments.value.filter(comment => comment.parentCommentId === null || comment.parentCommentId === undefined);
});

// 根据父评论ID获取子评论
const getSubComments = (parentId) => {
  return allComments.value.filter(comment => comment.parentCommentId === parentId);
};

// 获取帖子详情
const getPostDetail = async () => {
  try {
    const response = await axios.get(`api/forumById?postId=${postId}`);
    if (response.code === 200) {
      postDetail.value = response.data;
      // 将所有评论（包括子评论）放入allComments数组
      allComments.value = response.data.commentsList || [];
    }
  } catch (error) {
    console.error('获取帖子详情失败:', error);
  }
};
const user = useUserStore().user
// 提交评论
const submitComment = () => {

  if (!commentText.value.trim()) {
    return;
  }
  axios.post("api/comments/forumCommentAdd", {
    content: commentText.value,
    targetType: 'forum',
    targetId: postId,
    authorId: user.userId,
    parentCommentId: null // 主评论的parentCommentId为null
  }).then(res => {
    if (res.code === 200) {
      // 清空输入框
      commentText.value = '';
      // 刷新评论列表
      getPostDetail();
    } else {
      console.log("发布失败")
    }
  })
};

// 显示回复输入框
const showReplyInput = (comment, topLevelComment = null) => {
  replyingTo.value = comment.commentId;
  replyText.value = '';
  // 滚动到输入框位置
  setTimeout(() => {
    const inputElement = document.querySelector(`.reply-input-container, .sub-reply-input-container`);
    if (inputElement) {
      inputElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }
  }, 100);
};

// 取消回复
const cancelReply = () => {
  replyingTo.value = null;
  replyText.value = '';
};

// 提交回复
const submitReply =  (comment, topLevelComment = null) => {
  if (!replyText.value.trim()) {
    return;
  }
  
  try {
      axios.post('api/comments/forumCommentAdd', {
      content: replyText.value,
      targetType: 'forum',
      targetId: postId,
      authorId: user.userId,
      parentCommentId: comment.commentId,
      // 如果回复的是子评论，确保设置正确的parentCommentUser信息
      parentCommentUser: comment.user
    }).then(res=>{
          if (res.code === 200) {
              // 清空输入框和回复状态
              replyText.value = '';
              replyingTo.value = null;
              // 刷新评论列表
              getPostDetail();
          }
      })
  } catch (error) {
    console.error('提交回复失败:', error);
  }
};

// 格式化时间
const formatTime = (timeString) => {
  if (!timeString) return '';
  const date = new Date(timeString);
  const now = new Date();
  const diff = now - date;
  const minutes = Math.floor(diff / 60000);
  const hours = Math.floor(diff / 3600000);
  const days = Math.floor(diff / 86400000);
  
  if (minutes < 60) {
    return `${minutes}分钟前`;
  } else if (hours < 24) {
    return `${hours}小时前`;
  } else if (days < 30) {
    return `${days}天前`;
  } else {
    return timeString.split(' ')[0];
  }
};

// 返回上一页
const handleBack = () => {
  router.back();
};

// 组件挂载时获取帖子详情
onMounted(() => {
  getPostDetail();
});
</script>

<style scoped lang="less">
.forum-detail-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 80px;
}

.forum-detail-header {
  background-color: #fff;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 10;
}

.post-content {
  background-color: #fff;
  padding: 70px 16px 16px;
  margin-bottom: 10px;
}

.post-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 12px;
  color: #333;
}

.author-info {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.avatar {
  width: 36px;
  height: 36px;
  margin-right: 10px;
}

.author-details {
  display: flex;
  flex-direction: column;
}

.username {
  font-size: 14px;
  color: #333;
  margin-bottom: 2px;
}

.post-time {
  font-size: 12px;
  color: #999;
}

.post-text {
  font-size: 15px;
  line-height: 1.6;
  color: #333;
  margin-bottom: 16px;
  white-space: pre-wrap;
}

.cover-image {
  width: 100%;
  height: 200px;
  margin-bottom: 16px;
  border-radius: 8px;
}

.interaction-data {
  display: flex;
  justify-content: space-around;
  padding: 12px 0;
  border-top: 1px solid #eee;
}

.interaction-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #666;
}

.interaction-icon {
  font-size: 20px;
  margin-bottom: 4px;
}

.interaction-count {
  font-size: 12px;
}

.comments-section {
  background-color: #fff;
  padding: 16px;
}

.comments-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 16px;
  color: #333;
}

.comments-list {
  space-y: 16px;
}

.comment-item {
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-author-info {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.comment-avatar {
  width: 32px;
  height: 32px;
  margin-right: 8px;
}

.comment-author-details {
  display: flex;
  flex-direction: column;
}

.comment-username {
  font-size: 13px;
  color: #333;
  margin-bottom: 1px;
}

.comment-time {
  font-size: 11px;
  color: #999;
}

.comment-content {
  font-size: 14px;
  color: #333;
  line-height: 1.5;
  margin-bottom: 8px;
  padding-left: 40px;
}

.comment-actions {
  padding-left: 40px;
  margin-bottom: 8px;
}

.comment-action {
  font-size: 12px;
  color: #666;
  cursor: pointer;
  &:hover {
    color: #1989fa;
  }
}

/* 子评论区域样式 */
.sub-comments {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px dashed #eee;
}

.sub-comment-item {
  padding: 12px 0;
  background-color: #fafafa;
  border-radius: 8px;
  margin-top: 8px;
}

.sub-comment-inner {
  padding-left: 40px;
}

.sub-comment-author-info {
  display: flex;
  align-items: center;
  margin-bottom: 6px;
}

.sub-comment-avatar {
  width: 28px;
  height: 28px;
  margin-right: 6px;
}

.sub-comment-author-details {
  display: flex;
  flex-direction: column;
}

.sub-comment-username {
  font-size: 12px;
  color: #333;
  margin-bottom: 1px;
}

.sub-comment-time {
  font-size: 10px;
  color: #999;
}

.sub-comment-content {
  font-size: 13px;
  color: #333;
  line-height: 1.4;
  margin-bottom: 6px;
  padding-left: 34px;
}

.reply-to {
  color: #1989fa;
  font-size: 12px;
}

.sub-comment-actions {
  padding-left: 34px;
}

.sub-comment-action {
  font-size: 11px;
  color: #666;
  cursor: pointer;
  &:hover {
    color: #1989fa;
  }
}

/* 子评论的回复输入框样式 */
.sub-reply-input-container {
  margin-top: 12px;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 8px;
  margin-left: 40px;
}

/* 主评论的回复输入框样式 */
.reply-input-container {
  margin-top: 12px;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.reply-input {
  background-color: #fff;
  margin-bottom: 8px;
}

.reply-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.cancel-button {
  background-color: #fff;
  color: #666;
  border: 1px solid #ddd;
}

.submit-reply-button {
  background-color: #1989fa;
  color: #fff;
}

/* 子评论的回复列表样式 */
.sub-sub-comments {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px dashed #eee;
  margin-left: 40px;
}

.sub-sub-comment-item {
  padding: 10px 0;
  background-color: #f0f0f0;
  border-radius: 6px;
  margin-top: 6px;
}

.sub-sub-comment-inner {
  padding-left: 34px;
}

.sub-sub-comment-author-info {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.sub-sub-comment-avatar {
  width: 24px;
  height: 24px;
  margin-right: 4px;
}

.sub-sub-comment-author-details {
  display: flex;
  flex-direction: column;
}

.sub-sub-comment-username {
  font-size: 11px;
  color: #333;
  margin-bottom: 1px;
}

.sub-sub-comment-time {
  font-size: 9px;
  color: #999;
}

.sub-sub-comment-content {
  font-size: 12px;
  color: #333;
  line-height: 1.3;
  margin-bottom: 4px;
  padding-left: 28px;
}

.sub-sub-comment-actions {
  padding-left: 28px;
}

.sub-sub-comment-action {
  font-size: 10px;
  color: #666;
  cursor: pointer;
  &:hover {
    color: #1989fa;
  }
}

.no-comments {
  text-align: center;
  color: #999;
  padding: 40px 0;
  font-size: 14px;
}

.comment-input-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 12px 16px;
  border-top: 1px solid #eee;
  display: flex;
  align-items: center;
  gap: 12px;
}

.comment-input {
  flex: 1;
  background-color: #f5f5f5;
  border-radius: 20px;
  padding: 6px 16px;
}

.submit-button {
  background-color: #1989fa;
  color: #fff;
  border-radius: 20px;
  padding: 6px 20px;
  font-size: 14px;
}
</style>